var config = require('../lib/config');
var qs = require("qs");
var UserService = require("../service/user").UserService;
var logger = require('../service/logging').logger;

exports.midware_login = function(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    res.redirect('/login');
  }
}

exports.midware_login_admin = function(req, res, next) {
  if (req.session.adminuser) {
    next();
  } else {
    res.redirect('/login.html');
  }
}

exports.midware_login_wechat_rest = function(req,res,next){
  if(req.session.user_fw && req.session.user_fw.openid){
    return next();
  }else{
    res.json(401,{"success":false,"msg":"未找到openid","error":"未找到openid"});
  }
}

// openid绑定的中间件
exports.midware_login_wechat_binduser = function(req,res,next){
  if(req.session.user_fw){
    if(req.session.user_fw.user){
      return next();
    }else{
      var us = new UserService();
      us.getUserByOpenid(req.session.user_fw.openid,function(err,doc){
        if(err) return resErr(res,err);
        if(doc){
          req.session.user_fw.user = doc;
          return next();
        }else{
          return res.redirect("/views/bind");
        }
      })
    }
  }else{
    res.json(401,{"success":false,"msg":"未找到openid","error":"未找到openid"});
  }
}


// 服务号的登录中间件
exports.midware_login_wechat = function(req,res,next){
  if(req.session.user_fw){
    if(!req.session.user_fw.user){
      var us = new UserService();
      us.getUserByOpenid(req.session.user_fw.openid,function(err,doc){
        if(err) return resErr(res,err);
        if(doc){
          logger.info(doc);
          req.session.user_fw.user = doc;
        }
        return next();
      })
    }else{
      return next();
    }    
  }else{
    var url = config.wechat.auth_code_url;
    var query = {};    
    query.appid = config.wechat.appid;
    query.redirect_uri = config.wechat.redirect_uri;
    query.response_type = "code";
    query.scope = "snsapi_base";
    var curr_url = encodeURIComponent(req.url);
    if(curr_url.length <= 128){
      query.state = encodeURIComponent(req.url);  
    }    
    url = url + "?" + qs.stringify(query) + "#wechat_redirect";
    console.log(url);
    return res.redirect(url);
  }
}

exports.midware_crossdomain = function(req,res,next){
  res.setHeader("Access-Control-Allow-Methods","OPTIONS,POST,GET");
  res.setHeader("Access-Control-Allow-Headers","x-requested-with");
  res.setHeader("Access-Control-Allow-Origin", "*");
  next();
}
